package com.jp.boot.util;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Slf4j
public class SyFileUtil {
    /**
     * 转换MultipartFile对象为java.io.File类型
     *
     * @param multipartFile
     * @return
     */
    public static File convertMultipartFileToFile(MultipartFile multipartFile) {
        File result = null;
        try {
            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            result = File.createTempFile(UUID.randomUUID().toString(), suffix);
            multipartFile.transferTo(result);
            result.deleteOnExit();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 下载文件
     *
     * @param url 链接
     * @return 文件
     */
    public static File downloadFile(String url) {
        File result = null;
        try {
            String suffix = url.substring(url.lastIndexOf("."));
            result = File.createTempFile(UUID.randomUUID().toString(), suffix);
            HttpUtil.downloadFileFromUrl(url, result);
            result.deleteOnExit();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }
}
